package com.itheima.reggie.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private HttpSession session;
    //登录
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //接收处理请求参数
        String username = map.get("username");
        String password = map.get("password");
        //调用service进行登录操作
        ResultInfo resultInfo=employeeService.login(username,password);
        //如果用户登录成功了,向session中保存一个标识
        if (resultInfo.getCode()==1){
            Employee employee = (Employee) resultInfo.getData();
            session.setAttribute(Constant.SESSION_EMPLOYEE,employee);
        }
        //将结果返回
        return resultInfo;
    }
    //退出
    @PostMapping("/employee/logout")
    public ResultInfo logout(){
        //清除session中用户信息
        session.invalidate();
        //返回成功标识
        return ResultInfo.success(null);
    }

    //查询员工列表
    @GetMapping("/employee/find")
    public ResultInfo findList(String name){
        //调用service
        List<Employee> employeeList=employeeService.findByName(name);
        //返回查询结果
        return ResultInfo.success(employeeList);
    }
    //添加员工信息
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){
        //调用service
        employeeService.save(employee);
        //返回结果
        return ResultInfo.success(null);
    }
    //根据id查询员工
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        log.info("接收的id是"+id);//打印接收的id
        //调用service方法根据id进行查询
        Employee employee=employeeService.findById(id);
        //返回结果
        return ResultInfo.success(employee);
    }
    //修改员工信息
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
        //调用service进行更新
        employeeService.update(employee);
        //返回结果
        return ResultInfo.success(null);
    }
}
